package com.lagou.edu.servlet;

import com.lagou.edu.config.SpringConfig;
import com.lagou.edu.utils.JsonUtils;
import com.lagou.edu.pojo.Result;
import com.lagou.edu.service.TransferService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 应癫
 */
@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {


    private TransferService transferServiceProxy;

    @Override
    public void init() throws ServletException {
        try {
            transferServiceProxy = (TransferService)SpringConfig.getObjFromBeanMap(TransferService.class);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 设置请求的编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");

        Integer money = Integer.valueOf(req.getParameter("money"));

        Result result = new Result();
        try {
            transferServiceProxy.transfer(fromCardNo, toCardNo, money);
            result.setStatus("200");
            result.setMessage("转账成功");
        }catch (Exception ex){
            ex.printStackTrace();
            result.setStatus("500");
            result.setMessage("转账失败");
        }

        resp.setContentType("application/json;charset=utf-8");

        try {
            resp.getWriter().write(JsonUtils.object2Json(result));
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
